package com.ancy.backup.api;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ancy.backup.common.IErrorCode;
import com.ancy.backup.common.IMessage;
import com.ancy.backup.common.IParams;
import com.ancy.backup.utils.OAuth;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class LoginApi extends HttpServlet implements IErrorCode, IMessage,
		IParams {

	Gson gson = new Gson();
	HashMap<String, String> map = new HashMap<String, String>();
	Entity userProfile;
	DatastoreService datastore;
	String oAuthKey;
	Key key;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		if (req.getParameter(REQ_UNAME) == null
				|| req.getParameter(REQ_PASS) == null) {
			map.put(RES_STATUS, FAILURE);
			map.put(RES_CODE, INV_REQ);
		} else {
			datastore = DatastoreServiceFactory.getDatastoreService();
			key = KeyFactory.createKey(USER_ENTY, req.getParameter(REQ_UNAME));
			try {
				userProfile = datastore.get(key);
				if (userProfile.getProperty(REQ_PASS).equals(
						req.getParameter(REQ_PASS))) {
					OAuth oAuth = new OAuth();
					oAuthKey = oAuth.nextSessionId();
					userProfile.setProperty(REQ_OAUTH, oAuthKey);
					map.put(RES_STATUS, SUCCESS);
					map.put(RES_OAUTH, oAuthKey);
					map.put(RES_CODE, LOGIN_SUCCESS);
				} else {
					map.put(RES_STATUS, FAILURE);
					map.put(RES_CODE, USER_NT_VALID);
				}
			} catch (EntityNotFoundException e) {
				// TODO Auto-generated catch block
				map.put(RES_STATUS, FAILURE);
				map.put(RES_CODE, USER_NT_VALID);
			}
		}
		resp.getWriter().println(gson.toJson(map));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		  Enumeration enumV = req.getParameterNames();
	      while (enumV.hasMoreElements()) {
	    	  
	      }
	}
}
